﻿/*
 * Copyright(C) 2012,ajayumi 保留所有权利。( All rights reserved. )
 * 
 * 文件名称：CryptoProvider.cs
 * 摘    要：
 * 当前版本：1.0
 * 作    者：黄乙冬 (ajayumi)
 * 创建日期：2012年6月9日星期六
 */
using System.Configuration.Provider;
using System.Collections.Specialized;
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;

namespace ajayumi.Platform.Core.Security
{
    /// <summary>
    /// 字符串的加密解密相关内容
    /// </summary>
    public abstract class CryptoProvider : ProviderBase, IDisposable
    {
        public CryptoProvider(string name)
            : base()
        {
            NameValueCollection config = new NameValueCollection();
            this.Initialize(name, config);

            this.Init();
        }

        /// <summary>
        /// 初始化
        /// </summary>
        protected abstract void Init();

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainStr">需要加密的字符串</param>
        /// <returns>加密后的字符串</returns>
        public abstract string Encrypt(string plainStr);

        /// <summary>
        /// 解密
        /// </summary>
        /// <param name="encryptedStr">需要解密的字符串</param>
        /// <returns>解密后的字符串</returns>
        public abstract string Decrypt(string encryptedStr);


        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="input">需要加密的字符串</param>
        /// <returns></returns>
        public string GetMD5Hash(string input)
        {
            MD5 md5Hasher = MD5.Create();

            byte[] data = md5Hasher.ComputeHash(Encoding.Unicode.GetBytes(input));

            return Convert.ToBase64String(data);
        }

        protected byte[] HexToByte(string hexString)
        {
            byte[] returnBytes = new byte[hexString.Length / 2];
            for (int i = 0; i < returnBytes.Length; i++)
            { returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16); }
            return returnBytes;
        }

        protected string GetHexString(byte[] byteArray)
        {
            StringBuilder hexString = new StringBuilder(byteArray.Length * 2);
            for (int i = 0; i < byteArray.Length; i++)
                hexString.Append(string.Format("{0:X}", byteArray[i]));
            int x = hexString.Capacity;
            return hexString.ToString();
        }


        public abstract void Dispose();
    }
}
